﻿(function ($) {
    $(function () {
        var percentages = {};
        // WebUploader实例
        var GUID = WebUploader.Base.guid(); //当前页面是生成的GUID作为标示
        // 实例化
        var uploader = WebUploader.create({
            pick: {
                id: '#uploader',
                label: '点击选择文件'
            },
            formData: {
                uid: 123
            },
            swf: '/js/Uploader.swf',
            chunked: true, //分片处理大文件
            chunkSize: 2 * 1024 * 1024,
            server: 'http://localhost:8800/upload',
            disableGlobalDnd: true,
            threads: 1, //上传并发数
            //由于Http的无状态特征，在往服务器发送数据过程传递一个进入当前页面是生成的GUID作为标示
            formData: {},
            fileNumLimit: 300,
            compress: false, //图片在上传前不进行压缩
            fileSizeLimit: 1024 * 1024 * 1024,    // 1024 M
            fileSingleSizeLimit: 1024 * 1024 * 1024    // 1024 M
        });
        uploader.on('uploadBeforeSend', function (object, data, headers) {//上传加入队列之前触发
            console.info('uploadBeforeSend', object, data, headers);
            data.md5 = Global.GetFileQueued(data.id).md5;
            console.info('uploadBeforeSend', object, data, headers);
        });
        uploader.on('fileQueued', function (file) {//加入队列的时候触发
            var uploadTr = "<div class='tr clearfix'>";
            uploadTr += "<div class='td td1'>" + file.name + "</div>";
            uploadTr += "<div class='td td2'>" + WebUploader.formatSize(file.size) + "</div>";
            uploadTr += "<div class='td td3' id='" + file.id + "'>等待验证</div>";
            uploadTr += "</div>";

            $(".mainKuang").append(uploadTr);//在最后面添加一行
            $(".fixkuang").show(500);//显示kuang
            uploader.md5File(file)
                // 及时显示进度
                .progress(function (percentage) {
                    var fileObj = $('#' + file.id);
                    var spanObj = fileObj.html('正在验证文件:' + parseInt(percentage * 100) + '%');
                })
                // 获取上传进度
                .then(function (val) {
                    console.info('md5 result:', val, file);
                    $.extend(uploader.options.formData, { md5: val });
                    var fileObj = $('#' + file.id);
                    $.ajax({
                        url: '/Upload/GetMaxChunk',
                        async: true,
                        data: { md5: val, ext: file.ext },
                        success: function (response) {
                            console.info('response', response);
                            var res = JSON.parse(response);
                            Global.FileQueueds.push({ id: file.id, md5: val, size: file.size, ext: file.ext, chunk: res.data });
                            console.info('fileCheckMaxChunk', file, res.data);
                            fileObj.html('验证完成，等待上传').css('color', '#aaa');
                            ////文件验证完成后自动触发上传
                            percentages[file.id] = [file.size, 0];

                            if (res.code !== 0) {
                                // append tipkuang
                                fileObj.html('上传完成').css('color', '#aaa');
                                //返回文件ID
                                makeTree(res.code, file.name, file.ext);
                            } else {
                                //需要上传

                                uploader.upload();
                            }
                        }
                    });



                });
        });
        uploader.onUploadProgress = function (file, percentage) {

            //updateTotalProgress(file);
            var fileObj = $('#' + file.id);
            fileObj.html(Math.round(percentage * 100) + '%');
        };
        // 文件上传成功,合并文件。
        uploader.on('uploadSuccess', function (file, response) {
            console.info('uploadSuccess', file, response, file.id);
            if (response && response.code >= 0) {
                var dataObj = response.data;
                var md5 = Global.GetFileQueued(file.id).md5;
                console.info('uploadSuccess2', md5);
                if (dataObj.chunked) {
                    $.post('/Upload/MergeFiles',
                        { md5: md5, ext: dataObj.ext },
                        function (data) {
                            data = $.parseJSON(data);
                            if (data.hasError) {
                                alert('文件合并失败！');
                            } else {
                                var fileObj = $('#' + file.id);
                                //alert(decodeURIComponent(data.savePath));
                                fileObj.html('上传成功').css('color', 'blue');
                                console.info('上传文件完成并合并成功，触发回调事件');
                                console.log(file, "是文件名字吗");
                                makeTree(response.code, file.name, file.ext);
                                if (window.UploadSuccessCallback) {
                                    window.UploadSuccessCallback(file, md5);
                                }
                            }
                        });
                } else {
                    var fileObj = $('#' + file.id);
                    fileObj.html('上传成功').css('color', 'blue');
                    console.info('上传文件完成，不需要合并，触发回调事件');
                    if (window.UploadSuccessCallback) {
                        window.UploadSuccessCallback(file, md5);
                    }
                    makeTree(response.code, file.name, file.ext);
                }
            }
        });
        //-----
    });

})(jQuery);